import { Injectable } from '@angular/core';
import {Observable, Subject} from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class EventbusService {

  private subjectsmap: Map<string,Subject<any>>;
  public subject:Subject<any>;

  constructor() {
    this.subjectsmap=new Map<string, Subject<any>>();
  }

  publish(eventName: string,parm:string) {

    this.subject=this.subjectsmap.get(eventName)!;


    this.subject.next(parm);
  }


  on(eventName: string): Observable<any> {
// ensure a subject for the event name exists
    // this.subjects[eventName] = this.subjects[eventName] || new Subject();
    //alert('有消息开始注入'+eventName);
    if(this.subjectsmap.has(eventName)){
      this.subject=this.subjectsmap.get(eventName)!;
    }
    else {
      let temp=new Subject();
      this.subjectsmap.set(eventName,temp);
      this.subject=temp;
    }

// return observable
    return this.subject.asObservable();
  }
}
